//
//  WBOAuthController.swift
//  新浪微博
//
//  Created by 郭鹏飞 on 2016/11/25.
//  Copyright © 2016年 郭鹏飞. All rights reserved.
//

import UIKit
import SVProgressHUD

class WBOAuthController: UIViewController {
    
    private lazy var webView = UIWebView()
    
    override func loadView() {
        view = webView
        view.backgroundColor = UIColor.white
        
        //取消滚动视图
        webView.scrollView.isScrollEnabled = false
        
        //设置代理
        webView.delegate = self
        
        //设置 Nav
        title = "登录新浪微博"
        //Nav Btn
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "返回", fontSize: 14, target: self, action: #selector(close), isBack: true)
        
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", target:  self, action: #selector(autoFill))
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        
        //授权页面
        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(WBAPPKey)&redirect_uri=\(WBRedirectURL)"
        
        //1>确定要访问的资源
        guard let url = URL(string: urlString) else {
                
                return
        }
        //2.建立请求
        let request = URLRequest(url: url)
        
        //3.加载建立请求
        webView.loadRequest(request)

    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    //MARK: - 监听方法
    @objc func close(){
        
        SVProgressHUD.dismiss()
        dismiss(animated: true, completion: nil)
    }
    
    //自动填充 - WebView 的注入,直接修改本地浏览器中 缓存的内容
    //点击登录,执行 submit() 将本地的数据提交给服务器
    @objc private func autoFill() {
        
        //js
        let js = "document.getElementById('userId').value = '189837674@qq.com';" + "document.getElementById('passwd').value = 'guopengfei199447';"
        //webView 执行 js
        webView.stringByEvaluatingJavaScript(from: js)
        
    }
    

}

extension WBOAuthController: UIWebViewDelegate{
    
    //webView
    //要加载的请求
    //导航类型
    //是否加载 request
    func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        //确认思路
        //如果请求地址包含 http://www.tianup.cn 不加载页面 /否则加载页面

        
        //2. 从 网址 回调地址 的 查询字符串中查找
        //if 有 code 授权成功,否则失败
        
        //true/false/nil
        if request.url?.absoluteString.hasPrefix(WBRedirectURL) == false{
                return true
        }
        
         //print("加载请求\(request.url?.absoluteString)")
        
        //query 就是 URL 中 '?'后面的所有部分
         //print("加载请求\(request.url?.query)")
        
        //如果有,授权成功,否则,授权失败
        if request.url?.query?.hasPrefix("code=") == false {
            print("取消授权")
            close()
            
            return false
        }
        
        //3. 从 query 字符串中取出 授权码
        //代码走到此处, url 一定有查询字符串,并且包含 'code='
        
        let code = request.url?.query?.substring(from: "code=".endIndex) ?? ""
        print("获取授权码\(code)")
        
        //4.使用 授权码获取 AccessToken
        WBNetworkManager.shared.loadAccessToken(code){ (isSccuess) in
            if !isSccuess {
                SVProgressHUD.showInfo(withStatus: "网络请求失败")
            } else {
                //SVProgressHUD.showInfo(withStatus: "登录成功")
                
                //1. 通过通知 发送登录成功消息 - 不关心有没有监听者
                NotificationCenter.default.post(name: NSNotification.Name(rawValue: WBUserLoginSuccessedNotification), object: nil)
                
                //2.关闭窗口
                self.close()
            }
        }
        
        return false
    }
    
    func webViewDidStartLoad(_ webView: UIWebView) {
        SVProgressHUD.show()
    }
    
    func webViewDidFinishLoad(_ webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
}

